import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class CoreMemberService extends BaseService<any> {
  private readonly logger = new Logger(CoreMemberService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * modify
   * 对应 PHP: CoreMemberService_core::modify()
   * 逻辑类型: undefined - undefined
   */
  async modify(site_id: number, member_id: number, field: number, data: number) {
    // 基于PHP真实逻辑: modify
    // PHP原文: $field_name = match ( $field ) {             'nickname' => 'nickname',             'mobile' => 'mobile',             'id_card' => 'id_card',          ...
const field_name = match ( field ) {
            nickname: 'nickname',
            mobile: 'mobile',
            id_card: 'id_card',
            remark: 'remark',
            headimg: 'headimg',
            member_label: 'member_label',
            member_level: 'member_level',
            birthday: 'birthday',
            sex: 'sex',
  }

  /**
   * batchModify
   * 对应 PHP: CoreMemberService_core::batchModify()
   * 逻辑类型: undefined - undefined
   */
  async batchModify(site_id: any, data: any) {
    // 基于PHP真实逻辑: batchModify
    // PHP原文: $field = $data[ 'field' ];         $member_ids = $data[ 'member_ids' ];         $is_all = $data[ 'is_all' ];         $field_name = match ( $field ) { ...
const field = data[ 'field' ];
        const member_ids = data[ 'member_ids' ];
        const is_all = data[ 'is_all' ];
        const field_name = match ( field ) {
            member_label: 'member_label',
            member_level: 'member_level',
            const default => throw new AdminBusinessException("不支持的字段: field"),
  }

  /**
   * getInfoByMemberId
   * 对应 PHP: CoreMemberService_core::getInfoByMemberId()
   * 逻辑类型: undefined - undefined
   */
  async getInfoByMemberId(site_id: number, member_id: number, field: number) {
    // 基于PHP真实逻辑: getInfoByMemberId
    // PHP原文: $where = array(             [ 'site_id', '=', $site_id ],             [ 'member_id', '=', $member_id ]         );         return $this->model->where($...
const where = [
            [ 'site_id', '=', site_id ],
            [ 'member_id', '=', member_id )
        ];
        return this.model.where(where).field(field).findOrEmpty().toArray(];
    }

    /**
     * 查询会员实例
     * @param int site_id
     * @param int member_id
     * @return Member|array|mixed|Model
     */
    async find(int site_id, int member_id)
    {
        const where = [
            [ 'site_id', '=', site_id ],
            [ 'member_id', '=', member_id )
        ];
        return this.model.where(where).findOrEmpty(];
    }

    /**
     * 会员数量
     * @return int
     * @throws DbBusinessException
     */
    async getCount(where = [))
    {
        const condition = [];
        if (!!where[ 'site_id' ))) {
            condition[] = [ 'site_id', '=', where[ 'site_id' ] ];
  }

  /**
   * findRecord (原方法名: find)
   * 对应 PHP: CoreMemberService_core::find()
   * 逻辑类型: undefined - undefined
   * 注意: 为避免与BaseService方法冲突，已重命名
   */
  async findRecord(site_id: number, member_id: number) {
    // 基于PHP真实逻辑: find
    // PHP原文: $where = array(             [ 'site_id', '=', $site_id ],             [ 'member_id', '=', $member_id ]         );         return $this->model->where($...
const where = [
            [ 'site_id', '=', site_id ],
            [ 'member_id', '=', member_id )
        ];
        return this.model.where(where).findOrEmpty(];
    }

    /**
     * 会员数量
     * @return int
     * @throws DbBusinessException
     */
    async getCount(where = [))
    {
        const condition = [];
        if (!!where[ 'site_id' ))) {
            condition[] = [ 'site_id', '=', where[ 'site_id' ] ];
  }

  /**
   * getCount
   * 对应 PHP: CoreMemberService_core::getCount()
   * 逻辑类型: undefined - undefined
   */
  async getCount(where: any[]) {
    // 基于PHP真实逻辑: getCount
    // PHP原文: $condition = array();         if (!empty($where[ 'site_id' ])) {             $condition[] = [ 'site_id', '=', $where[ 'site_id' ] ];...
const condition = [];
        if (!!where[ 'site_id' ))) {
            condition[] = [ 'site_id', '=', where[ 'site_id' ] ];
  }

  /**
   * createMemberNo
   * 对应 PHP: CoreMemberService_core::createMemberNo()
   * 逻辑类型: undefined - undefined
   */
  async createMemberNo(site_id: number) {
    // 基于PHP真实逻辑: createMemberNo
    // PHP原文: $site = ( new Site() )->where([ [ 'site_id', '=', $site_id ] ])->lock(true)->find();         $config = ( new CoreMemberConfigService() )->getMemberCon...
const site = ( this.siteService ).where([ [ 'site_id', '=', site_id ) )).lock(true).find(];
        const config = ( this.coreMemberConfigService ).getMemberConfig(site_id];

        const no = site.member_no + 1;
        const member_no = config[ 'prefix' ) . ( strlen(config[ 'prefix' )) > config[ 'length' ] ? no : str_pad(no, ( config[ 'length' ) - strlen(config[ 'prefix' )) ), "0", STR_PAD_LEFT) ];

        const member = ( this.memberService ).where([ [ 'site_id', '=', site_id ], [ 'member_no', '=', member_no ) )).findOrEmpty(];

        if (member.isEmpty()) {
            return member_no;
  }

  /**
   * setMemberNo
   * 对应 PHP: CoreMemberService_core::setMemberNo()
   * 逻辑类型: undefined - undefined
   */
  async setMemberNo(site_id: number, member_id: number) {
    // 基于PHP真实逻辑: setMemberNo
    // PHP原文: $site = ( new Site() )->where([ [ 'site_id', '=', $site_id ] ])->lock(true)->find();         $config = ( new CoreMemberConfigService() )->getMemberCon...
const site = ( this.siteService ).where([ [ 'site_id', '=', site_id ) )).lock(true).find(];
        const config = ( this.coreMemberConfigService ).getMemberConfig(site_id];

        const no = site.member_no + 1;
        const member_no = config[ 'prefix' ) . ( strlen(config[ 'prefix' )) > config[ 'length' ] ? no : str_pad(no, ( config[ 'length' ) - strlen(config[ 'prefix' )) ), "0", STR_PAD_LEFT) ];

        const member = ( this.memberService ).where([ [ 'site_id', '=', site_id ], [ 'member_no', '=', member_no ) )).findOrEmpty(];

        // 变更站点最大会员码值
        site.save([ member_no: no )];

        if (member.isEmpty()) {
            ( this.memberService ).update([ member_no: member_no ], [ [ 'site_id', '=', site_id ], [ 'member_id', '=', member_id ) )];
  }

  /**
   * sendGrowth
   * 对应 PHP: CoreMemberService_core::sendGrowth()
   * 逻辑类型: undefined - undefined
   */
  async sendGrowth(site_id: any[], member_id: any[], key: any[], param: any[]) {
    // 基于PHP真实逻辑: sendGrowth
    // PHP原文: $config = ( new CoreMemberConfigService() )->getGrowthRuleConfig($site_id);         if (!isset($config[ $key ]) || empty($config[ $key ]) || empty($co...
const config = ( this.coreMemberConfigService ).getGrowthRuleConfig(site_id);
        if (!typeof config[ key )) || !config[ key )) || !config[ key ][ 'is_use' ))) return true;

        const config = config[ key ];

        const dict = ( new DictLoader("GrowthRule") ).load(];
        if (!typeof dict[ key ))) return true;
        const dict = dict[ key ];

        const growth = config[ 'growth' ] || 0;
        if (typeof dict[ 'calculate' )) && !!dict[ 'calculate' ))) {
            const calculate = dict[ 'calculate' ];
            if (calculate instanceof \Closure) {
                const growth = calculate(config, param);
            } else if (class_exists(calculate)) {
                const growth = ( new calculate() ).handle(config, param);
            }
  }

  /**
   * sendPoint
   * 对应 PHP: CoreMemberService_core::sendPoint()
   * 逻辑类型: undefined - undefined
   */
  async sendPoint(site_id: any[], member_id: any[], key: any[], param: any[]) {
    // 基于PHP真实逻辑: sendPoint
    // PHP原文: $config = ( new CoreMemberConfigService() )->getPointRuleConfig($site_id)[ 'grant' ] ?? [];         if (!isset($config[ $key ]) || empty($config[ $key...
const config = ( this.coreMemberConfigService ).getPointRuleConfig(site_id)[ 'grant' ] || [];
        if (!typeof config[ key )) || !config[ key )) || !config[ key ][ 'is_use' ))) return true;

        const config = config[ key ];

        const dict = ( new DictLoader("PointRule") ).load()[ 'grant' ] || [];
        if (!typeof dict[ key ))) return true;
        const dict = dict[ key ];

        const point = config[ 'point' ] || 0;
        if (typeof dict[ 'calculate' )) && !!dict[ 'calculate' ))) {
            const calculate = dict[ 'calculate' ];
            if (calculate instanceof \Closure) {
                const point = calculate(config, param);
            } else if (class_exists(calculate)) {
                const point = ( new calculate() ).handle(config, param);
            }
  }

  /**
   * memberGiftGrant
   * 对应 PHP: CoreMemberService_core::memberGiftGrant()
   * 逻辑类型: undefined - undefined
   */
  async memberGiftGrant(site_id: any[], member_id: any[], gifts: any[], param: any[]) {
    // 基于PHP真实逻辑: memberGiftGrant
    // PHP原文: try {             $dict = ( new DictLoader("MemberGift") )->load();              foreach ($gifts as $key => $item) {                 if (!$item[ 'is_u...
try {
            const dict = ( new DictLoader("MemberGift") ).load(];

            foreach (gifts as key => item) {
                if (!item[ 'is_use' ) || !typeof dict[ key )) || !typeof dict[ key ][ 'grant' )) || !dict[ key ][ 'grant' ))) continue;
                try {
                    const grant = dict[ key ][ 'grant' ];
                    if (grant instanceof \Closure) {
                        grant(site_id, member_id, item, param);
                    } else if (class_exists(grant)) {
                        ( new grant() ).handle(site_id, member_id, item, param);
                    }
                } catch (BusinessException e) {
                    Log.write('会员礼包' . key  + '发放失败，错误原因：' . e.getMessage() . e.getFile() . e.getLine();
  }
            return true;
  }

  /**
   * getGiftContent
   * 对应 PHP: CoreMemberService_core::getGiftContent()
   * 逻辑类型: undefined - undefined
   */
  async getGiftContent(site_id: any[], gifts: any[], scene: any[]) {
    // 基于PHP真实逻辑: getGiftContent
    // PHP原文: $dict = ( new DictLoader("MemberGift") )->load();          foreach ($gifts as $k => $item) {             $gifts[ $k ][ 'content' ] = null;            ...
const dict = ( new DictLoader("MemberGift") ).load(];

        foreach (gifts as k => item) {
            gifts[ k ][ 'content' ] = null;
            if (!typeof item[ 'is_use' )) || !item[ 'is_use' ] || !typeof dict[ k ][ 'content' )) || !dict[ k ][ 'content' )) || !typeof dict[ k ][ 'content' ][ scene ))) {
                continue;
            } } } else {
                const content = dict[ k ][ 'content' ][ scene ];
                if (content instanceof \Closure) {
                    gifts[ k ][ 'content' ] = content(site_id, item);
                } else if (class_exists(content)) {
                    gifts[ k ][ 'content' ] = ( new content() ).handle(site_id, item);
                }
            }
  }

  /**
   * getBenefitsContent
   * 对应 PHP: CoreMemberService_core::getBenefitsContent()
   * 逻辑类型: undefined - undefined
   */
  async getBenefitsContent(site_id: any[], benefits: any[], scene: any[]) {
    // 基于PHP真实逻辑: getBenefitsContent
    // PHP原文: $dict = ( new DictLoader("MemberBenefits") )->load();          foreach ($benefits as $k => $item) {             $benefits[ $k ][ 'content' ] = null;  ...
const dict = ( new DictLoader("MemberBenefits") ).load(];

        foreach (benefits as k => item) {
            benefits[ k ][ 'content' ] = null;
            if (!typeof item[ 'is_use' )) || !item[ 'is_use' ] || !typeof dict[ k ][ 'content' )) || !dict[ k ][ 'content' )) || !typeof dict[ k ][ 'content' ][ scene ))) {
                continue;
            } } } else {
                const content = dict[ k ][ 'content' ][ scene ];
                if (content instanceof \Closure) {
                    benefits[ k ][ 'content' ] = content(site_id, item);
                } else if (class_exists(content)) {
                    benefits[ k ][ 'content' ] = ( new content() ).handle(site_id, item);
                }
            }
  }

  /**
   * getGrowthRuleContent
   * 对应 PHP: CoreMemberService_core::getGrowthRuleContent()
   * 逻辑类型: undefined - undefined
   */
  async getGrowthRuleContent(site_id: any[], config: any[], scene: any[]) {
    // 基于PHP真实逻辑: getGrowthRuleContent
    // PHP原文: $dict = ( new DictLoader("GrowthRule") )->load();          foreach ($config as $k => $item) {             $config[ $k ][ 'content' ] = null;          ...
const dict = ( new DictLoader("GrowthRule") ).load(];

        foreach (config as k => item) {
            config[ k ][ 'content' ] = null;
            if (!typeof item[ 'is_use' )) || !item[ 'is_use' ] || !typeof dict[ k ][ 'content' )) || !dict[ k ][ 'content' )) || !typeof dict[ k ][ 'content' ][ scene ))) {
                continue;
            } } } else {
                const content = dict[ k ][ 'content' ][ scene ];
                if (content instanceof \Closure) {
                    config[ k ][ 'content' ] = content(site_id, item);
                } else if (class_exists(content)) {
                    config[ k ][ 'content' ] = ( new content() ).handle(site_id, item);
                }
            }
  }

  /**
   * getPointGrantRuleContent
   * 对应 PHP: CoreMemberService_core::getPointGrantRuleContent()
   * 逻辑类型: undefined - undefined
   */
  async getPointGrantRuleContent(site_id: any[], config: any[], scene: any[]) {
    // 基于PHP真实逻辑: getPointGrantRuleContent
    // PHP原文: $dict = ( new DictLoader("PointRule") )->load()[ 'grant' ];          foreach ($config as $k => $item) {             $config[ $k ][ 'content' ] = null;...
const dict = ( new DictLoader("PointRule") ).load()[ 'grant' ];

        foreach (config as k => item) {
            config[ k ][ 'content' ] = null;
            if (!typeof item[ 'is_use' )) || !item[ 'is_use' ] || !typeof dict[ k ][ 'content' )) || !dict[ k ][ 'content' )) || !typeof dict[ k ][ 'content' ][ scene ))) {
                continue;
            } } } else {
                const content = dict[ k ][ 'content' ][ scene ];
                if (content instanceof \Closure) {
                    config[ k ][ 'content' ] = content(site_id, item);
                } else if (class_exists(content)) {
                    config[ k ][ 'content' ] = ( new content() ).handle(site_id, item);
                }
            }
  }

  /**
   * getPointConsumeRuleContent
   * 对应 PHP: CoreMemberService_core::getPointConsumeRuleContent()
   * 逻辑类型: undefined - undefined
   */
  async getPointConsumeRuleContent(site_id: any[], config: any[], scene: any[]) {
    // 基于PHP真实逻辑: getPointConsumeRuleContent
    // PHP原文: $dict = ( new DictLoader("PointRule") )->load()[ 'consume' ];          foreach ($config as $k => $item) {             $config[ $k ][ 'content' ] = nul...
const dict = ( new DictLoader("PointRule") ).load()[ 'consume' ];

        foreach (config as k => item) {
            config[ k ][ 'content' ] = null;
            if (!typeof item[ 'is_use' )) || !item[ 'is_use' ] || !typeof dict[ k ][ 'content' )) || !dict[ k ][ 'content' )) || !typeof dict[ k ][ 'content' ][ scene ))) {
                continue;
            } } } else {
                const content = dict[ k ][ 'content' ][ scene ];
                if (content instanceof \Closure) {
                    config[ k ][ 'content' ] = content(site_id, item);
                } else if (class_exists(content)) {
                    config[ k ][ 'content' ] = ( new content() ).handle(site_id, item);
                }
            }
  }
}
